import os

import cv2
import numpy as np
from tqdm import tqdm

from option import parse_args
from abnormal.multiple_actors_statistics import cmp_video_name


def videos_mean(diffs, func, template: str, less_equal_than=0.):
    video_names = os.listdir(diffs)
    video_names.sort(key=cmp_video_name)
    for video_name in tqdm(video_names):
        mean_min, mean_max = 255., 0.
        video_path = os.path.join(diffs, video_name)
        count_less_equal_than = 0
        for diff in os.listdir(video_path):
            mask = cv2.imread(os.path.join(video_path, diff), cv2.IMREAD_GRAYSCALE)
            mean_min = min(mean_min, np.mean(mask))
            mean_max = max(mean_max, np.mean(mask))
            if np.mean(mask) <= less_equal_than:
                count_less_equal_than += 1
        # sub = mean_max - mean_min
        if mean_min <= less_equal_than and count_less_equal_than < 10:
            func(template.format(video_name, mean_min, mean_max, count_less_equal_than))


def main():
    args = parse_args()
    diffs = os.path.join(args.root_dir, 'diffs')
    args.save = True
    if args.save:
        with open('abnormal_mean_statistics.dat', 'w') as f:
            videos_mean(diffs, f.write, '{},{:.2f},{:.2f},{}\n', 10.)
    else:
        videos_mean(diffs, print, '{},{:.2f},{:.2f},{}', 10.)


if __name__ == '__main__':
    main()
